<template>
<div class="device-rate full-height bg-white page-content content relative-position">
  <collapse ref="collapse">
    <template v-slot:content>
      <div style="padding: 0 20px;">
        <div class="margin-t-20 form-inline" style="padding: 0; display: block">
          <div class="flex justify-between no-wrap">
            <div class="left box flex">
              <div class="margin-r-20">
                <customized-switch
                  style="width: 192px; height: 24px;margin-top: 2px"
                  :options="dateTypeOption"
                  v-model="dateType"
                />
              </div>
                <div class="margin-r-20 padding-b-20">
                <date-picker
                  format="YYYY-MM-DD"
                  :clearable="false" :editable="false"
                  :type="dateType" v-model="dateRange"
                  range placeholder="选择时间范围"
                  style="width: 240px"
                  v-show="dateType === 'date'"
                />
                <date-picker
                  format="YYYY-MM-DD"
                  :clearable="false" :editable="false"
                  :type="dateType" v-model="weekRange"
                  range placeholder="选择时间范围"
                  style="width: 240px"
                  v-show="dateType === 'week'"
                  @change="changeSelRange()"
                />
                <date-picker
                  format="YYYY-MM"
                  :clearable="false" :editable="false"
                  :type="dateType" v-model="monthRange"
                  range placeholder="选择时间范围"
                  style="width: 240px"
                  v-show="dateType === 'month'"
                />
              </div>
              <select-tree label="所在位置" :sel-tree="queryParams.location"
                           class="margin-r-15" ref="selectTree"
                           :tree-list="locationOptions" node-key="hash"
                           @treeChange="_changeTreeNode" />
              <select-tooltip v-model="queryParams.devices"
                              :options="devicesOption"
                              msg="设备"/>
<!--              <q-select
                class="select multipe-select margin-b-20"
                multiple
                outlined dense emit-value map-options options-dense
                ref="multipeSelect"
                @input="selDevice"
                :options="devicesOption"
                v-model="queryParams.devices"
                style="margin-right: 50px"
              >
                <q-tooltip v-if="queryParams.devices.length > 0">
                  <span v-for="(item,index) in queryParams.devices" :key="index">
                    <span v-if="item == 'all'">全部 </span>
                    <span v-else>{{devicesMap[item]}} </span>
                  </span>
                </q-tooltip>
                <template v-slot:no-option>
                  <div class="no-option"/>
                </template>
                <template v-slot:before>
                  <span class="form-name">设备:</span>
                </template>
              </q-select>-->
            </div>
            <div class="flex no-wrap">
              <q-btn
                class="btn margin-r-10"
                outline dense emit-value map-options options-dense
                color="primary"
                @click="resetSearch()"
                label="重置"
              />
              <q-btn class="btn" unelevated type="submit" color="primary" label="查询" @click="searchData()" />
            </div>
          </div>
          <div style="padding-bottom: 14px" class="flex justify-between items-center">
            <q-btn class="btn margin-r-10"
                   outline
                   color="primary"
                   label="导出Excel"
                   :disable="!tableData.length || isDisable"
                   @click="exportExcel"/>
            <div>
                <span style="margin-right: 6px;cursor: pointer" @click="dialogVisible=true">
                  <q-icon name="iconfont icontubiao-72" class="font-18 text-grey"/>
                  <q-tooltip max-width="300px">
                    <div>
                      时间开动率=实际加工时长/计划工作时长 x100%
                    </div>
                    <div>
                      性能开动率=理论加工时长/实际加工时长x100%
                    </div>
                    <div>
                      合格率=(完工数-不良数)/完工数x100%
                    </div>
                    <div>
                      设备稼动率=时间开动率×性能开动率x合格率
                    </div>
                  </q-tooltip>
                </span>
              <q-toggle v-model="showScale"
                        label="启用缩放"
                        left-label
                        class="toggle-space"
                        @input="changeScale"
              />
            </div>
          </div>

        </div>
      </div>
    </template>
  </collapse>
  <div style="flex: 1;padding: 0 20px;" class="margin-b-20 scroll-y scrollbar">
    <div id="scrollTop"></div>
    <!-- 图表的标题 -->
    <div class="flex items-center justify-between margin-b-20" style="margin-top: 6px">
      <div class="flex items-center">
        <div>{{selLocation}}</div>
          <div>{{`设备稼动率分析（${getDate(this.selDateRange[0])} ~ ${getDate(this.selDateRange[1])}） ${this.selDeviceId.label}`}}</div>
      </div>
    </div>
    <div ref="OEERate" style="width: 100%; height: 400px"></div>
    <div style="width: 100%;" class="margin-t-20">
      <div class="q-table__container q-table--cell-separator q-table__card q-table--no-wrap scroll stick-first-col no-hover" style="margin: 0;max-height: 730px">
          <div class="q-table__middle scroll" style="max-height: 550px" @scroll="scrollTable">
            <table class="q-table" id="table" ref="table">
            <thead>
              <tr>
                  <th class="text-left" style="width: 400px;z-index: 20">设备</th>
                <th class="text-center" v-for="(item,index) in theadList" :key="index" style="padding: 0">
                    <div style="height: 43px; line-height: 43px">{{item}}</div>
                  <div class="items-center justify-between" style="height: 43px; display: flex" v-if="params.type === 1">
                    <div v-for="(i, Iindex) in shiftInfoList[index]" :key="Iindex" class="flex-1 text-center">{{i.shiftName}}</div>
                  </div>
                </th>
              </tr>
            </thead>
            <tbody>
              <template v-for="(item,index) in tableData">
                <tr :key="index">
                    <td style="padding: 0;min-width: 360px" class="" :class="!idIndex? 'title-cell':''" v-for="(iTd,idIndex) in item.tr" :key="index+'_'+idIndex">
                      <div class="full-height flex" v-if="!idIndex">
                        <div class="text-left device-name flex bor-right">
                          <div class="name-cell flex items-center justify-center">
                            <div class="ellipsis-12-lines">{{iTd.deviceName}}</div>
                    </div>
                          </div>
                        <div class="full-height td-detail">
                          <div class="flex bor-bottom td-item-min justify-between">
                            时间开动率(A)
                            <tips tips="实际加工时长/计划工作时长" class="margin-r-10" />
                          </div>
                          <div class="flex bor-bottom td-item-min justify-between">
                            性能开动率(P)
                            <tips tips="理论加工时长/实际加工时长" class="margin-r-10" />
                      </div>
                          <div class="flex bor-bottom td-item-min justify-between">
                            合格率(Q)
                            <tips tips="合格数量/完工数量" class="margin-r-10" />
                          </div>
                          <div class="full-width td-item-min flex justify-between color-oee">设备稼动率（OEE）
                            <tips tips="A*P*Q" class="margin-r-10" />
                          </div>
                        </div>
                      </div>
                      <div class="td-detail" v-else  style="display: flex">
                            <div v-for="(v, vIndex) in params.type === 1 ? iTd.shiftInfos : [item.tr[idIndex]]" :key="index+'_'+idIndex + '_' + vIndex"
                                 :style="params.type === 1 ? { width: `${100/ (iTd.shiftInfos.length)}%` } : { flex : 1} " class="bor-right"
                            :class="params.type === 1 && vIndex == iTd.shiftInfos.length - 1 && 'color-blue'">
                              <div class="flex  bor-bottom item td-item-min">
                                {{iTd.isFuture ? '--' : `${getPercentage(v.availability)}%`}}
                                <q-tooltip>
                                    <div>计划工作时长: {{getDuration(v.planTime)}}</div>
                                    <div>实际加工时长: {{getDuration(v.actualTime)}} </div>
                                </q-tooltip>
                              </div>
                              <div class="flex  bor-bottom item td-item-min">{{iTd.isFuture ? '--' : `${getPercentage(v.performance)}%`}}
                                <q-tooltip>
                                  <div>理论加工时长: {{getDuration(v.academicBeat)}}</div>
                                  <div>实际加工时长: {{getDuration(v.actualBeat)}} </div>
                                </q-tooltip>
                              </div>
                              <div class="flex  bor-bottom item td-item-min">{{iTd.isFuture ? '--' : `${getPercentage(v.quality)}%`}}
                                <q-tooltip>
                                  <div>合格数量: {{(v.actualCount - v.badCount).toFixed()}} </div>
                                  <div>完工数量: {{v.actualCount}}</div>
                                </q-tooltip></div>
                              <div class="flex  item td-item-min color-oee">{{iTd.isFuture ? '--' : `${getPercentage(v.oee)}%`}}</div>
                            </div>
                        </div>
                    </td>
                </tr>
              </template>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

    <drawer
      title="说明"
      :visible.sync="dialogVisible"
      width="500px"
      close-on-click-modal>
      <div>
        <div>1.当日数据不计算</div>
        <div>2.时间开动率：设备实际加工状态总时长/计划工作时长（无论是过去时间，还是当天，计划工作时长都是整个轮班时长-休息时间）x 100%</div>
        <div>3.性能开动率：理论节拍（加工产品工序的理论工序节拍）/实际节拍（设备实际加工状态总时长）x 100%</div>
        <div>4.合格率：（完工数-不良数）/完工数 x 100%</div>
        <div>5.如果当日切换班制了则第二日生效新班制，也就是第二日按照新班制计算计划工作时长</div>
        <div>6..月和周计算公式同上，需要把每日/每周的各项值累加后再进行计算</div>
      </div>
    </drawer>
  </div>
</template>

<script>
import refreshMixin from '../../assets/js/refresh-mixin'
import Collapse from 'src/components/collapse'
import CustomizedSwitch from 'src/components/customized-switch'
import SelectTree from 'src/components/select-tree'
import moment from 'moment'
import echarts from 'echarts'
import _ from 'lodash'
import {
  getDeviceIds,
  getOrganize,
  getOEEDailyReport,
  getOEEWeeklyReport,
  getOEEMonthlyReport,
  exportOEEReport
} from '../../boot/statistics/device-rate'
import { defaultSchemesClearer } from '../../assets/js/util'
import { getOeeRateChart } from './components/get-oee-rate-chart'
import exportStat from './components/stat-export'
import { addListener } from 'resize-detector'
// import { exportUtilizationRateExcel } from './components/exportUtilizationRateExcel'
import { mapGetters } from 'vuex'
import Drawer from 'src/components/drawer/drawer'

moment.locale('zh-cn')

export default {
  name: 'device-rate',
  mixins: [refreshMixin],
  components: {
    Collapse,
    CustomizedSwitch,
    SelectTree,
    Drawer
  },
  data () {
    return {
      dialogVisible: false,
      showScale: false, // 是否可以缩放
      thumbStyle: this.CommonConfig.thumbStyle, // 滚动条样式
      tableData: [], // 当前显示数据
      allData: [], // 全部数据
      tableColumns: [],
      // 表格不分页
      pagination: {
        rowsPerPage: 0
      },
      dateRange: [moment(new Date()).subtract(7, 'days').toDate(), moment(new Date()).subtract(1, 'days').toDate()],
      weekRange: [null, null],
      monthRange: [null, null],
      selDateRange: [moment(new Date()).subtract(7, 'days').toDate(), new Date()],
      value: [],
      locationOptions: [], // 所在位置数据源
      devicesOption: [{
        'label': '全部',
        'value': 'all'
      }], // 设备下拉数据
      devicesMap: {}, // 设备详细
      dateTypeOption: [
        {
          value: 'date',
          label: ' 日 '
        },
        {
          value: 'week',
          label: ' 周 '
        },
        {
          value: 'month',
          label: ' 月 '
        }
      ],
      dateType: 'date',
      isOver: false,
      queryParams: {
        location: {}, // 所在位置
        devices: ['all']
      }, // 查询区条件
      selDeviceId: {
        label: '',
        value: 'all'
      }, // 选择设备
      selLocation: '', // 所选组织
      OEERateChart: null, // 稼动率图表
      chartsXLabel: [],
      theadList: [],
      rangeDiff: null,
      // 图表显示数据
      Availability: [],
      Performance: [],
      QualityRate: [],
      shiftInfoList: [],
      OEE: [],
      // 各设备图表待显示数据
      AvailabilityList: {},
      PerformanceList: {},
      QualityRateList: {},
      OEEList: {},
      params: {}, // 请求参数
      isDisable: false, // 导出按钮禁用
      isInit: true,
      excelData: null
    }
  },
  created () {
    this.init()
  },
  computed: {
    ...mapGetters([
      'userInfo', 'client'
    ])
  },
  watch: {
    showScale (val) {
      this.OEERateChart._model.option.dataZoom[0].disabled = !this.showScale
    }
  },
  mounted () {
    addListener(this.$refs.OEERate, this.$utils.debounce(() => {
      if (this.OEERateChart) {
        this.OEERateChart.resize()
      }
    }, 100))
  },
  methods: {
    // 图表缩放
    changeScale () {
      let option = _.cloneDeep(this.OEERateChart.getOption())
      option.dataZoom[0].disabled = !this.showScale
      this.OEERateChart.clear()
      this.OEERateChart.setOption(option)
    },
    /**
     * 全局刷新数据
     */
    refreshInfo () {
      this.isInit = true
      this.resetSearch()
    },
    // 初始化
    init () {
      this.getOrganize()
    },
    // 表格触底加载
    scrollTable (e) {
      if (e.target.scrollTop + e.target.offsetHeight > e.target.scrollHeight - 100) {
        this.loadMore()
        // 加载更多
      }
    },
    // 加载更多
    loadMore () {
      if (this.tableData.length < this.allData.length) {
        const allData = _.cloneDeep(this.allData)
        const showData = _.chunk(allData, this.tableData.length + 5)[0]
        const addData = _.chunk(showData, this.tableData.length)[1]
        this.tableData = _.concat(this.tableData, addData)
        console.log(this.tableData, '表格触底加载')
      }
    },
    // 选择设备
    selDevice (details) {
      // console.log(details)
      const selItem = this.queryParams.devices.find(item => {
        return item === 'all'
      })
      if (details[details.length - 1] === 'all') {
        if (selItem) {
          this.queryParams.devices = ['all']
        }
      } else {
        if (selItem) {
          const selList = this.queryParams.devices.splice(this.queryParams.devices.length - 1)
          this.queryParams.devices = selList
        }
      }
    },
    // 选择组织机构树节点 *
    _changeTreeNode: function (val) {
      if (val.id && val.label && val.hash) {
        this.queryParams.location.id = val.id
        this.queryParams.location.level = val.level
        this.queryParams.location.label = val.label
        this.queryParams.location.hash = val.hash
        this.queryParams.station = null
        this.getDevices(val.id, val.level)
      } else {
        this.selectFirstLocation()
        this.queryParams.station = null
      }
    },
    // 获取组织下设备列表
    getDevices (schemeId, schemeLevel) {
      getDeviceIds(schemeId, schemeLevel, true).then(res => {
        const ret = res.data
        const member = ret.list.map(v => {
          const item = v
          item.label = `${v.name}(${v.assetNumber || '--'})`
          item.value = v.id
          return item
        })
        this.devicesOption = [{
          'label': '全部',
          'value': 'all'
        }]
        this.devicesOption.push(...member)

        this.devicesMap = {}
        this.devicesOption.forEach(item => {
          this.devicesMap[item.value] = item.label
        })
        this.queryParams.devices = ['all']
      }).finally(() => {
        if (this.isInit) {
          this.isInit = !this.isInit
          this.searchData()
        }
      })
    },
    // 搜索
    searchData () {
      if (!this.checkSelRange()) {
        this.selLocation = this.queryParams.location.label
        // 所选设备为0
        if ((this.queryParams.devices[0] === 'all' && this.devicesOption.length <= 1) || (this.queryParams.devices[0] !== 'all' && this.queryParams.devices < 1)) {
          this.$message.warning('所选设备数量为0，请重新选择')
        } else {
          this.getAxisList()
        }
      }
    },
    // 拼接表头
    getAxisList () {
      this.chartsXLabel = []
      this.theadList = []
      if (this.dateType === 'date') {
        const startDate = moment(this.dateRange[0])
        const endDate = moment(this.dateRange[1])
        this.selDateRange = [startDate, endDate]
        this.rangeDiff = endDate.diff(startDate, 'days')
        for (let i = 0; i <= this.rangeDiff; i++) {
          const firstDate = moment(this.dateRange[0])
          const date = firstDate.add(i, 'd').format('MM-DD')
          this.chartsXLabel.push(date)
          this.theadList.push(`${date} ${firstDate.format('dddd')}`)
        }
      } else if (this.dateType === 'week') {
        const startDate = moment(this.weekRange[0])
        const endDate = moment(this.weekRange[1])
        this.selDateRange = [startDate.startOf('week'), endDate.endOf('week')]
        this.rangeDiff = endDate.diff(startDate, 'week')

        for (let i = 0; i <= this.rangeDiff; i++) {
          const firstDate = moment(this.weekRange[0])
          const date = firstDate.add(i, 'week')
          const weekStart = date.startOf('week').format('MM-DD')
          const weekEnd = date.endOf('week').format('MM-DD')
          const label = date.format('Wo')
          this.chartsXLabel.push(`第${label}`)
          this.theadList.push(`第${label} (${weekStart}~${weekEnd})`)
        }
      } else if (this.dateType === 'month') {
        const startDate = moment(this.monthRange[0])
        const endDate = moment(this.monthRange[1])
        this.selDateRange = [startDate.startOf('month'), endDate.endOf('month')]
        this.rangeDiff = endDate.diff(startDate, 'month')
        for (let i = 0; i <= this.rangeDiff; i++) {
          const firstDate = moment(this.monthRange[0])
          const date = firstDate.add(i, 'month').format('YYYY-MM')
          this.chartsXLabel.push(date)
          this.theadList.push(date)
        }
      }
      console.log(this.theadList)
      // 获取数据
      this.getDataList()
    },
    // 获取数据参数
    getDataList () {
      let params = {
        schemeLevelName: this.queryParams.location.label,
        schemeLevelId: this.queryParams.location.id,
        schemeLevel: this.queryParams.location.level
      }
      if (this.queryParams.devices[0] !== 'all') {
        params['deviceIds'] = this.queryParams.devices
        params['deviceCount'] = this.queryParams.devices.length
      } else {
        params['deviceCount'] = this.devicesOption.length - 1
      }
      this.selDeviceId.label = `${params.deviceCount}台设备`
      switch (this.dateType) {
        case 'date':
          params['startDate'] = moment(this.dateRange[0]).format('YYYY-MM-DD')
          params['endDate'] = moment(this.dateRange[1]).format('YYYY-MM-DD')
          params['type'] = 1
          this.getOEEDailyReport(params)
          break
        case 'week':
          params['startWeek'] = moment(this.weekRange[0]).isoWeekYear() + '' + moment(this.weekRange[0]).format('WW')
          params['endWeek'] = moment(this.weekRange[1]).isoWeekYear() + '' + moment(this.weekRange[1]).format('WW')
          params['type'] = 2
          this.getOEEWeeklyReport(params)
          break
        case 'month':
          params['startMonth'] = moment(this.monthRange[0]).format('YYYYMM')
          params['endMonth'] = moment(this.monthRange[1]).format('YYYYMM')
          params['type'] = 3
          this.getOEEMonthlyReport(params)
          break
      }
      this.params = params
    },
    // 是否为未来日期
    isFuture (date) {
      return moment(new Date()).diff(moment(date), 'days') <= 0
    },
    // 日稼动率
    getOEEDailyReport (params) {
      getOEEDailyReport(params).then(res => {
        this.excelData = _.cloneDeep(res)
        this.getTableData(res)
      })
    },
    // 周稼动率
    getOEEWeeklyReport (params) {
      getOEEWeeklyReport(params).then(res => {
        this.excelData = _.cloneDeep(res)
        this.getTableData(res)
      })
    },
    // 周稼动率
    getOEEMonthlyReport (params) {
      getOEEMonthlyReport(params).then(res => {
        this.excelData = _.cloneDeep(res)
        this.getTableData(res)
      })
    },
    getTableData (res) {
      let AvailabilityList = []
      let PerformanceList = []
      let QualityRateList = []
      let OEEList = []
      let tableData = []
      this.shiftInfoList = []
      const ret = res.data.reduce((arr, item) => {
        const obj = {
          ...item,
          oeeInfos: item.oeeInfos.map(v => {
            return {
              ...v,
              shiftInfos: _.concat(v.shiftInfos, [{ ...v, shiftName: '当天' }])
            }
          })
        }
        arr.push(obj)
        return arr
      }, [])
      if (res.data.length) {
        ret.forEach(device => {
          let deviceItem = { tr: [] }
          deviceItem.tr.push({
            deviceId: device.deviceId,
            deviceName: _.isNil(device.deviceName) ? '--' : device.deviceName
          })
          device.oeeInfos.forEach((item, index) => {
            let date
            switch (this.dateType) {
              case 'date':
                item.isFuture = this.isFuture(item.date)
                break
              case 'week':
                date = moment(this.weekRange[0]).add(index, 'week').startOf('week').format('YYYY-MM-DD')
                item.isFuture = this.isFuture(date)
                break
              case 'month':
                date = moment(this.monthRange[0]).add(index, 'month').format('YYYY-MM-DD')
                item.isFuture = this.isFuture(date)
                break
            }
            // 图表数据(取首行)
            if (_.isNil(device.deviceId)) {
              AvailabilityList.push(item.isFuture ? null : item.availability * 100)
              PerformanceList.push(item.isFuture ? null : item.performance * 100)
              QualityRateList.push(item.isFuture ? null : item.quality * 100)
              OEEList.push(item.isFuture ? null : item.oee * 100)
            }
            deviceItem.tr.push(item)
            // 默认显示全部
            this.Availability = AvailabilityList
            this.Performance = PerformanceList
            this.QualityRate = QualityRateList
            this.OEE = OEEList
          })
          tableData.push(deviceItem)
        })
      }

      this.shiftInfoList = ret[0].oeeInfos.map(v => {
        return v.shiftInfos || []
      })
      console.log(tableData)
      this.AvailabilityList = AvailabilityList
      this.PerformanceList = PerformanceList
      this.QualityRateList = QualityRateList
      this.OEEList = OEEList
      this.allData = tableData // 全部数据
      this.tableData = _.chunk(tableData, 5)[0] // 当前显示数据
      // 刷新数据
      this.refreshData()
    },
    // 刷新图表数据
    refreshData () {
      if (this.OEERateChart) {
        this.OEERateChart.clear()
        // 绘制图表
        const option = getOeeRateChart(this.chartsXLabel, this.Availability, this.Performance, this.QualityRate, this.OEE)
        this.OEERateChart.setOption(option)
      } else {
        // 基于准备好的dom，初始化echarts实例
        this.$nextTick(function () {
          this.OEERateChart = echarts.init(this.$refs.OEERate)
          // 绘制图表
          const option = getOeeRateChart(this.chartsXLabel, this.Availability, this.Performance, this.QualityRate, this.OEE)
          this.OEERateChart.setOption(option)
        })
      }
    },
    // 获取组织机构树
    getOrganize () {
      getOrganize().then(res => {
        // 去除 default 节点
        let clearTree = defaultSchemesClearer.clear(res.data)

        // 重新组织 tree
        clearTree.forEach(reorganize)

        function reorganize (node) {
          // 如果当前节点是工位，将 opname 挪到 label
          if (node.level === 5) {
            node.label = node.opname
          }

          // 为节点添加唯一键，用于 tree 组件标识唯一节点
          node.uniqueKey = node.level + ':' + node.id

          if (node.children instanceof Array) {
            node.children.forEach(reorganize)
          }
        }

        this.locationOptions = clearTree
        this.selectFirstLocation()
      })
    },
    // 选中第一个组织
    selectFirstLocation () {
      if (this.locationOptions.length === 0) {
        return
      }

      const first = this.locationOptions[0]
      this.queryParams.location.id = first.id
      this.queryParams.location.level = first.level
      this.queryParams.location.label = first.label
      this.queryParams.location.hash = first.hash
      this.$refs.selectTree.setValue(this.queryParams.location)
      this.getDevices(first.id, first.level)
    },
    /**
     * 重置查询条件
     */
    resetSearch () {
      this.queryParams.location = Object.assign({}, this.locationOptions[0])
      this.$refs.selectTree.setValue(this.queryParams.location)
      this._changeTreeNode(this.queryParams.location)
      this.queryParams.devices = ['all']
      this.queryParams.status = null
      this.dateRange = [moment(new Date()).subtract(7, 'days').toDate(), moment(new Date()).subtract(1, 'days').toDate()]
      this.dateType = 'date'
      this.weekRange = []
      this.monthRange = []
    },
    // 导出excel
    exportExcel () {
      this.isDisable = true
      this.$q.loading.show()
      const theadList = this.theadList.map(item => {
        return {
          field: 'field',
          name: item
        }
      })

      const excelHead = _.concat({
        field: 'field',
        name: '设备'
      }, theadList)

      console.log(excelHead, '表头')

      const params = [{ name: '设备稼动率分析' }]
      const res = this.$getUploadPath(params, '')
      this.requestId = res.fileNameNew
      this.params['requestId'] = res.fileNameNew
      this.params['excelHead'] = excelHead
      this.onSubscribe()

      exportOEEReport(this.params).then(res => {
        if (res.code !== '1200') {
          this.$showErrTips('导出异常，请稍后重试')
          this.closeUbscribeTopic()
        }
      }).catch(res => {
        console.log(res)
        this.closeUbscribeTopic()
      })

      // const dataRange = `${this.getDate(this.selDateRange[0])} ~ ${this.getDate(this.selDateRange[1])}`
      // const companyName = this.userInfo.company_name ? this.userInfo.company_name : '语祯物联'
      // const position = `所在位置: ${this.queryParams.location && this.queryParams.location.label}`
      // const stopReason = `设备稼动率分析${dataRange}共${this.selDeviceId.label}`
      // const sheetName = `${dataRange}设备稼动率分析`
      // const excelName = `${dataRange}${this.queryParams.location && this.queryParams.location.label}设备稼动率分析`
      // exportUtilizationRateExcel(companyName, stopReason, position, this.excelData, this.theadList, sheetName, excelName)
    },
    getExcelName () {
      const dataRange = `${this.getDate(this.selDateRange[0])} ~ ${this.getDate(this.selDateRange[1])}`
      // const companyName = this.userInfo.company_name ? this.userInfo.company_name : '语祯物联'
      // const position = `所在位置: ${this.queryParams.location && this.queryParams.location.label}`
      // const stopReason = `设备稼动率分析${dataRange}共${this.selDeviceId.label}`
      // const sheetName = `${dataRange}设备稼动率分析`
      const excelName = `${dataRange}${this.queryParams.location && this.queryParams.location.label}设备稼动率分析`
      return excelName
    },
    async onMessageArrived (message) {
      let msg = JSON.parse(message.body).data
      if (msg.requestId !== this.requestId) {
        return
      }
      if (msg.code + '' !== '200') {
        this.$showErrTips('导出异常，请稍后重试')
        this.closeUbscribeTopic()
        return
      }
      await this.$saveFileForBlob(msg.data, `${this.getExcelName()}.xls`)
      this.closeUbscribeTopic()
      this.$message.success('数据请求成功,请保存文件')
    },

    onSubscribe () {
      if (this.client) {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.uploadFile.subscribeTopic}${this.requestId}`, this.onMessageArrived, { id: `${this.params.requestId}` }
        )
        this.$q.loading.hide()
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    closeUbscribeTopic () {
      this.isDisable = false
      this.client.unsubscribe(`${this.params.requestId}`)
      this.$q.loading.hide()
    },
    // 获取时间
    getDate (val) {
      return moment(val).format('YYYY-MM-DD')
    },
    getDuration (val) {
      return exportStat.getDuration(val)
    },
    getPercentage (val) {
      return exportStat.getPercentage(val)
    },
    // 修改所选区间
    changeSelRange () {
      this.weekRange[0] = moment(this.weekRange[0]).startOf('week').toDate()
      this.weekRange[1] = moment(this.weekRange[1]).endOf('week').toDate()
    },
    // 校验所选区间
    checkSelRange () {
      let isOver = false
      let isNil = false
      let tips = ''
      if (this.dateType === 'date') {
        isNil = _.isNil(this.dateRange[0]) && _.isNil(this.dateRange[1])
        isOver = Math.abs(moment(this.dateRange[0]).diff(moment(this.dateRange[1]), 'days')) > 60
        tips = '(日视图下,日期范围最大不可超过60天)'
      } else if (this.dateType === 'week') {
        isNil = _.isNil(this.weekRange[0]) && _.isNil(this.weekRange[1])
        isOver = Math.abs(moment(this.weekRange[0]).diff(moment(this.weekRange[1]), 'weeks')) > 10
        tips = '(周视图下,日期范围最大不可超过10周)'
      } else if (this.dateType === 'month') {
        isNil = _.isNil(this.monthRange[0]) && _.isNil(this.monthRange[1])
        isOver = Math.abs(moment(this.monthRange[0]).diff(moment(this.monthRange[1]), 'months')) > 24
        tips = '(月视图下,日期范围最大不可超过24月)'
      }

      if (isNil) {
        this.$message.warning('所选日期范围不可为空')
      } else if (isOver) {
        this.$message.warning(`所选日期范围已超出${tips}`)
      }
      return isOver || isNil
    }
  }
}
</script>

<style scoped lang="stylus">

.device-rate {
  /*.scroll-flag{
    position relative
    top -48px
  }*/
  // 无边框下拉

  >>> .q-field--borderless .q-field__ {
    &control, &append {
      height 21px
      min-height 21px
      padding-left 5px
      min-height 21px !important
    }

    &control-container {
      line-height: 21px;
      padding: 0 !important
      height 21px
    }

    &native {
      padding 0
      min-height 21px !important

      & span {
        line-height 21px
      }
    }
  }

  >>> .q-field__marginal {
    font-size 16px
    color black
    font-weight 400
    text-align right
  }

  >>> .q-table {
    & td {
      background-color #fff !important
    }

    & td:hover {
      background-color #fff !important
    }
  }
  //@media (max-width $breakpoint-md-max) {
  //  .td-height {
  //    height 7 * $td-md-height
  //  }
  //
  //  .name-cell {
  //    max-height 7 * $td-md-height + 13px
  //  }
  //}
  //@media (min-width $breakpoint-lg-min) and (max-width $breakpoint-lg-max) {
  //  .td-height {
  //    height 7 * $td-lg-height
  //  }
  //
  //  .name-cell {
  //    height 7 * $td-lg-height + 13px
  //  }
  //}
  //@media (min-width $breakpoint-xl-min) {
  //  .td-height {
  //    height 7 * $td-xl-height
  //  }
  //
  //  .name-cell {
  //    height 7 * $td-xl-height + 13px
  //  }
  //}

  .td-detail {
    /*height 336*/
    .bor-right {
      border-right $border
    }

    .bor-bottom {
      border-bottom $border
    }

    .item {
      box-sizing border-box
    }

    .bg-grey {
      background-color #F9F9F9 !important
    }
  }

  .flex-1 {
    flex 1
  }

  .td-item-min {
    padding-left 20px
    padding-right 20px
  }

  .title-cell {
    min-width 400px
    max-width 400px

    .device-name {
      width 140px
      min-width 130px

      padding-left 30px
      padding-right 20px
      height 100%
      border-right $border

      .name-cell {
        width 100%
        padding-top 20px
        padding-bottom 20px
        white-space normal

        .ellipsis-12-lines {
          max-height 253px
          overflow: hidden;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 12;
          line-clamp: 12;
        }
      }
    }

    .td-detail {
      flex 1
    }
  }
}
</style>
<style lang="scss">
.color-blue{
  div{
    color: #000;
    background: #F2F2F2
  }
}
.color-oee{
  color: #000;
  background: #F2F2F2
}
</style>
